using IQIGame.Onigao.Game.Editors;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;


public class CFSMGeneratorWindow : EditorWindow
{
    private DropdownField DF_Configs;
    private TextField TF_EntityClassName;
    private Label L_EntityClassTip;
    private Button Btn_Generate;
    private List<string> filePaths = new List<string>();
    private List<string> fileNames = new List<string>();
    private string fsmConfigDir;
    private Type[] _typesInGamePlayDLL;
    private Type _entityType;

    public static void ShowWindow()
    {
        CFSMGeneratorWindow wnd = GetWindow<CFSMGeneratorWindow>();
        wnd.titleContent = new GUIContent("生成状态机代码");
    }

    public void CreateGUI()
    {
        // Import UXML
        var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Scripts/FrameworkExt/Editor/ConfigurableFSM/Window/CFSMGeneratorWindow.uxml");
        VisualElement root = visualTree.Instantiate();
        rootVisualElement.Add(root);

        DF_Configs = root.Q<DropdownField>("DF_Configs");
        DF_Configs.choices = CreateCfgOptions();
        DF_Configs.index = 0;
        TF_EntityClassName = root.Q<TextField>("TF_EntityClassName");
        TF_EntityClassName.RegisterValueChangedCallback(OnEntityClassNameChanged);
        L_EntityClassTip = root.Q<Label>("L_EntityClassTip");
        L_EntityClassTip.text = "未找到实体Class";
        L_EntityClassTip.style.color = Color.red;

        Btn_Generate = root.Q<Button>("Btn_Generate");
        Btn_Generate.clicked += OnClickGenerate;

        // 加载程序集，这里需要你提供程序集的名称或路径
        Assembly assembly = Assembly.Load("IQIGameGamePlayAssembly");
        // 获取程序集中的所有类型
        _typesInGamePlayDLL = assembly.GetTypes();
    }

    private List<string> CreateCfgOptions()
    {
        string assetDir = Application.dataPath;
        string rootDir = assetDir.Substring(0, assetDir.Length - "Assets".Length);
        fsmConfigDir = rootDir + "StateMachine/source";
        string[] files = Directory.GetFiles(fsmConfigDir, "*.graphml", SearchOption.AllDirectories);
        foreach (var file in files)
        {
            filePaths.Add(file);
            fileNames.Add(EdtCfgFSMUtil.GetCfgFileName(fsmConfigDir, file));
        }
        List<string> list = fileNames.Clone();
        list.Insert(0, "空");
        return list;
    }

    private void OnEntityClassNameChanged(ChangeEvent<string> evt)
    {
        // 标记是否找到类
        _entityType = null;
        // 遍历所有类型
        foreach (Type type in _typesInGamePlayDLL)
        {
            // 检查类型的名称是否是"MyClass"
            if (evt.newValue.Contains('.') && type.FullName == evt.newValue)
            {
                _entityType = type;
                break;
            }
            else if (type.Name == evt.newValue)
            {
                _entityType = type;
                break;
            }
        }
        if (_entityType != null)
        {
            L_EntityClassTip.text = _entityType.FullName;
            L_EntityClassTip.style.color = Color.green;
        }
        else
        {
            L_EntityClassTip.text = "未找到实体Class";
            L_EntityClassTip.style.color = Color.red;
        }
    }

    private void OnClickGenerate()
    {
        int index = DF_Configs.index;
        int fileIndex = index - 1;
        if (index == 0)
        {
            Debug.LogError("请选择配置。");
            return;
        }
        if (_entityType == null)
        {
            Debug.LogError("请填写正确的实体类。");
            return;
        }
        string filePath = filePaths[fileIndex];
        CfgFSMExporter exporter = CfgFSMExporter.Create(fsmConfigDir, filePath);
        if (exporter == null)
        {
            Debug.LogError($"导出失败。root：{fsmConfigDir}, path：{filePath}");
            return;
        }
        List<string> expiredCodePaths = new List<string>();
        if (exporter.CheckExpiredCode(expiredCodePaths))
        {
            List<string> codeNames = new List<string>();
            foreach (var codePath in expiredCodePaths)
            {
                codeNames.Add(Path.GetFileNameWithoutExtension(codePath));
            }
            if (EditorUtility.DisplayDialog("警告", $"存在已过期代码：{string.Join(", ", codeNames)}", "全部清理", "稍后自行清理"))
            {
                foreach (var path in expiredCodePaths)
                {
                    File.Delete(path);
                }
            }
        }
        //生成代码
        exporter.ExportCode(_entityType.FullName);
        Debug.Log("生成成功。");
    }
}